package com.zyz.web.book.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyz.web.book.entity.Book;
import com.zyz.web.book.entity.BookPageParam;
import com.zyz.web.book.service.BookService;
import com.zyz.utils.ResultUtils;
import com.zyz.utils.ResultVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/book")
public class BookController {
    @Autowired
    private BookService bookService;
    //新增
    @PostMapping
    public ResultVo add(@RequestBody Book book){
        if(bookService.save(book)){
            return ResultUtils.success("添加成功！");
        }
        return ResultUtils.error("添加失败！");
    }
    //修改
    @PutMapping
    public ResultVo edit(@RequestBody Book book){
        if(bookService.updateById(book)){
            return ResultUtils.success("编辑成功！");
        }
        return ResultUtils.error("编辑失败！");
    }
    //删除
    @DeleteMapping("/{id}")
    public ResultVo delete(@PathVariable("id") Integer id){
        if(bookService.removeById(id)){
            return ResultUtils.success("删除成功！");
        }
        return ResultUtils.error("删除失败！");
    }
    //列表
    @GetMapping("/list")
    public ResultVo list(BookPageParam param){
        IPage<Book> page = new Page<>(param.getCurrentPage(),param.getPageSize());
        //构造查询条件
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(param.getBookName())){
            queryWrapper.lambda().like(Book::getBookName,param.getBookName());
        }
        //分页查询
        IPage<Book> bookIPage = bookService.page(page,queryWrapper);
        return ResultUtils.success("查询成功！",bookIPage);
    }
    //批量删除
    @DeleteMapping("/deleteMultipleByIds")
    public ResultVo deleteMultipleByIds(@RequestParam List<Integer> ids){
        System.out.println(ids);
        if(bookService.deleteMultipleByIds(ids)){
            return ResultUtils.success("批量删除成功");
        }
        return ResultUtils.error("批量删除失败");
    }
    //获取单个图书信息
    @GetMapping("/{id}")
    public ResultVo getOneBook(@PathVariable Integer id){
        Book bookInfo =bookService.getOneBook(id);
        if(bookInfo!=null){
            return ResultUtils.success("查看成功",bookInfo);
        }
        return ResultUtils.error("查看失败");
    }
}
